package org.groupg.practice;

import cn.hutool.core.io.FileUtil;
import org.apache.daffodil.japi.*;
import org.apache.daffodil.japi.Compiler;
import org.apache.daffodil.japi.infoset.InfosetOutputter;
import org.apache.daffodil.japi.infoset.NullInfosetOutputter;
import org.apache.daffodil.japi.io.InputSourceDataInputStream;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class DFDLExample {

    public static void main(String[] args) throws IOException {
        // 初始化 Daffodil 编译器

        Compiler compiler = Daffodil.compiler();

        ProcessorFactory pf = compiler.compileFile(new File("src/main/resources/schema.dfdl.xsd"));
        DataProcessor processor = pf.onPath("/");

//        Compiler

//        // 编译 DFDL 模式
//        DataProcessor processor;
//        try {
//            processor = compiler.compileSource(new File("schema.dfdl.xsd").toURI()).onPath("/records");
//        } catch (Exception e) {
//            System.err.println("编译模式失败:");
//            e.printStackTrace();
//            return;
//        }

        // 检查编译错误
        if (processor.isError()) {
            System.err.println("模式错误:");
            for (Diagnostic d : processor.getDiagnostics()) {
                System.err.println(d.getMessage());
            }
            return;
        }

        // 示例输入数据
        String inputData =
                "John@|@Doe@|@25$|$\n" +
                        "Alice@|@Smith@|@30$|$\n";

        // 创建输入流
        ByteArrayInputStream inputStream = new ByteArrayInputStream(
                inputData.getBytes(StandardCharsets.UTF_8)
        );


        // 解析数据
        InputSourceDataInputStream dataInputStream = new InputSourceDataInputStream(inputStream);
        InfosetOutputter outputter = new NullInfosetOutputter();
        ParseResult result = processor.parse(dataInputStream, outputter);

        // 处理解析结果
        if (result.isError()) {
            System.err.println("解析错误:");
            for (Diagnostic d : result.getDiagnostics()) {
                System.err.println(d.getMessage());
            }
        } else {
            // 输出 XML 结果
            System.out.println("解析成功:\n" + result.getDiagnostics().toString());
        }
    }
}